<?php

/**
 * ECSHOP 管理中心文章处理程序文件
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: article.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . "includes/fckeditor/fckeditor.php");
require_once(ROOT_PATH . 'includes/cls_image.php');

require_once(ROOT_PATH . '/includes/oss-sdk/Object.php');

/*初始化数据交换对象 */
$exc   = new exchange($ecs->table("article"), $db, 'article_id', 'title');
$image = new cls_image();

/* 允许上传的文件类型 */
//$allow_file_types = '|GIF|JPG|PNG|BMP|SWF|DOC|XLS|PPT|MID|WAV|ZIP|RAR|PDF|CHM|RM|TXT|';
$allow_file_types = '|GIF|JPG|JEPG|PNG|BMP|SWF|';
// 最大上传文件大小
$php_maxsize = ini_get('upload_max_filesize');
$htm_maxsize = '2M';

/*------------------------------------------------------ */
//-- 文章列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
    /* 取得过滤条件 */
    admin_priv('article_look');
    $filter = array();
    $smarty->assign('cat_select',  article_cat_list(0));
    $smarty->assign('ur_here',      $_LANG['03_article_list']);
    $smarty->assign('action_link',  array('text' => $_LANG['article_add'], 'href' => 'article.php?act=add'));
    $smarty->assign('full_page',    1);
    $smarty->assign('filter',       $filter);

    $article_list = get_articleslist();
	$sql = 'select article_id  from '.$GLOBALS['ecs']->table('article_article').' order by article_id';
	$count = $db->GetAll($sql);
	foreach($article_list['arr'] as $key => $var){
		$m=0;
		foreach($count as $k => $v){
			
			if($v['article_id']==$var['article_id']){
				$m++;
			}
		}
		$article_list['arr'][$key]['article_link']=$m;
	}
	$sql = 'select article_id  from '.$GLOBALS['ecs']->table('goods_article').' order by article_id';
	$count = $db->GetAll($sql);
	foreach($article_list['arr'] as $key => $var){
		$m=0;
		foreach($count as $k => $v){
			
			if($v['article_id']==$var['article_id']){
				$m++;
			}
		}
		$article_list['arr'][$key]['goods_article']=$m;
	}

	
    $smarty->assign('article_list',    $article_list['arr']);
    $smarty->assign('filter',          $article_list['filter']);
    $smarty->assign('record_count',    $article_list['record_count']);
    $smarty->assign('page_count',      $article_list['page_count']);

    $sort_flag  = sort_flag($article_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    assign_query_info();
    $smarty->display('article_list.htm');
}

/*------------------------------------------------------ */
//-- 翻页，排序
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    check_authz_json('article_look');

    $article_list = get_articleslist();
	$sql = 'select article_id  from '.$GLOBALS['ecs']->table('article_article').' order by article_id';
	$count = $db->GetAll($sql);
	foreach($article_list['arr'] as $key => $var){
		$m=0;
		foreach($count as $k => $v){
			
			if($v['article_id']==$var['article_id']){
				$m++;
			}
		}
		$article_list['arr'][$key]['article_link']=$m;
	}
	$sql = 'select article_id  from '.$GLOBALS['ecs']->table('goods_article').' order by article_id';
	$count = $db->GetAll($sql);
	foreach($article_list['arr'] as $key => $var){
		$m=0;
		foreach($count as $k => $v){
			
			if($v['article_id']==$var['article_id']){
				$m++;
			}
		}
		$article_list['arr'][$key]['goods_article']=$m;
	}
    $smarty->assign('article_list',    $article_list['arr']);
    $smarty->assign('filter',          $article_list['filter']);
    $smarty->assign('record_count',    $article_list['record_count']);
    $smarty->assign('page_count',      $article_list['page_count']);

    $sort_flag  = sort_flag($article_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('article_list.htm'), '',
        array('filter' => $article_list['filter'], 'page_count' => $article_list['page_count']));
}

/*------------------------------------------------------ */
//-- 添加文章
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'add')
{
    /* 权限判断 */
    admin_priv('article_manage');

    /* 创建 html editor */
    create_html_editor('FCKeditor1');

    /*初始化*/
    $article = array();
    $article['is_open'] = 1;
    $article['author'] = $GLOBALS['db']->getOne('SELECT nick_name FROM ' .$GLOBALS['ecs']->table('admin_user'). " WHERE user_name = '$_SESSION[admin_name]'");
	
    /* 取得分类、品牌 */
    $smarty->assign('goods_cat_list', cat_list());
    $smarty->assign('brand_list',     get_brand_list());

    /* 清理关联商品 */
    $sql = "DELETE FROM " . $ecs->table('goods_article') . " WHERE article_id = 0";
    $db->query($sql);

    if (isset($_GET['id']))
    {
        $smarty->assign('cur_id',  $_GET['id']);
    }
	$sql=" select keyword from ".$GLOBALS['ecs']->table('admin_keywords')." where admin_id='$_SESSION[admin_id]' order by count desc limit 0,20 ";
	$getkeywords=$GLOBALS['db']->getAll($sql);
	$smarty->assign('getkeywords',     $getkeywords);
	$sql=" select * from".$GLOBALS['ecs']->table('copyright_type');	
	$getcopyright_type=$GLOBALS['db']->getAll($sql);
	$smarty->assign('getcopyright_type',$getcopyright_type);
    $smarty->assign('article',     $article);
    $smarty->assign('cat_select',  article_cat_list(0));
    $smarty->assign('ur_here',     $_LANG['article_add']);
    $smarty->assign('action_link', array('text' => $_LANG['03_article_list'], 'href' => 'article.php?act=list'));
    $smarty->assign('form_action', 'insert');

    assign_query_info();
    $smarty->display('article_info.htm');
}

/*------------------------------------------------------ */
//-- 添加文章
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'insert')
{
    /* 权限判断 */
    admin_priv('article_manage');
//	ini_set('upload_max_filesize','1024M');
    /*检查是否重复*/
    $is_only = $exc->is_only('title', $_POST['title'],0, " cat_id ='$_POST[article_cat]'");

    if (!$is_only)
    {
        sys_msg(sprintf($_LANG['title_exist'], stripslashes($_POST['title'])), 1);
    }
	// 文章缩图验证
	    if (isset($_FILES['file']['error'])) // php 4.2 版本才支持 error

    {
    	
		if ($_FILES['file']['error'] == 0)

        {

            if (!$image->check_img_type($_FILES['file']['type']))

            {

               sys_msg($_LANG['dthumbimg_url']);

            }

        }
    	 if ($_FILES['file']['error'] == 1)

        {

            if (!$image->check_img_type($_FILES['file']['type']))

            {

               sys_msg(sprintf($_LANG['thumbimg_url_too_big'],$php_maxsize), 1,  array(), false);

            }

        }

        elseif ($_FILES['file']['error'] == 2)

        {

            sys_msg(sprintf($_LANG['thumbimg_url_too_big'], $php_maxsize), 1, array(), false);

        }


    }else{
    	if ($_FILES['file']['tmp_name'] != 'none')

        {

            if (!$image->check_img_type($_FILES['file']['type']))

            {



                 sys_msg($_LANG['dthumbimg_url']);;

            }

        }
    }
		// 视频缩图验证
	    if (isset($_FILES['img']['error'])) // php 4.2 版本才支持 error

    {
    	
		if ($_FILES['img']['error'] == 0)

        {

            if (!$image->check_img_type($_FILES['img']['type']))

            {

               sys_msg($_LANG['vidioimg_url']);

            }

        }
    	 if ($_FILES['img']['error'] == 1)

        {

            if (!$image->check_img_type($_FILES['img']['type']))

            {

               sys_msg(sprintf($_LANG['vidioimg_url_too_big'],$php_maxsize), 1,  array(), false);

            }

        }

        elseif ($_FILES['img']['error'] == 2)

        {

            sys_msg(sprintf($_LANG['vidioimg_url_too_big'], $php_maxsize), 1, array(), false);

        }


    }else{
    	if ($_FILES['img']['tmp_name'] != 'none')

        {

            if (!$image->check_img_type($_FILES['file']['type']))

            {



                 sys_msg($_LANG['vidioimg_url']);;

            }

        }
    }
	// 图文图片验证
	foreach ($_FILES['img_url']['error'] AS $key => $value) {
		
		if ($value == 0) {
			if (!$image -> check_img_type($_FILES['img_url']['type'][$key])) {
				sys_msg(sprintf($_LANG['invalid_img_url'], $key + 1), 1, array(), false);
			}
		} elseif ($value == 1) {
			sys_msg(sprintf($_LANG['img_url_too_big'], $key + 1, $php_maxsize), 1, array(), false);
		} elseif ($_FILES['img_url']['error'] == 2) {
			sys_msg(sprintf($_LANG['img_url_too_big'], $key + 1, $htm_maxsize), 1, array(), false);
		}
	}

    /* 取得文件地址 */
    $file_url = '';
    if ((isset($_FILES['file']['error']) && $_FILES['file']['error'] == 0) || (!isset($_FILES['file']['error']) && isset($_FILES['file']['tmp_name']) && $_FILES['file']['tmp_name'] != 'none'))
    {
        // 检查文件格式
        if (!check_file_type($_FILES['file']['tmp_name'], $_FILES['file']['name'], $allow_file_types))
        {
            sys_msg($_LANG['invalid_file']);
        }

        // 复制文件
        $res = check_article_file($_FILES['file']);
        if ($res != false)
        {
            $file_url = $res;
		    /* 上传图片到oss*/			
			uploadFile($ossClient, $bucket, $file_url, $_FILES['file']['tmp_name'],$_FILES['file']['type']);				
        }
    }

    if ($file_url == '')
    {
        $file_url = $_POST['file_url'];
    }
	/* 取得视频地址 */
    $img_url = '';
    if ((isset($_FILES['img']['error']) && $_FILES['img']['error'] == 0) || (!isset($_FILES['img']['error']) && isset($_FILES['img']['tmp_name']) && $_FILES['img']['tmp_name'] != 'none'))
    {
        // 检查文件格式
        if (!check_file_type($_FILES['img']['tmp_name'], $_FILES['img']['name'], $allow_file_types))
        {
            sys_msg($_LANG['invalid_file']);
        }

        // 复制文件
        $res = check_article_file($_FILES['img']);
        if ($res != false)
        {
            $img_url = $res;
		    /* 上传图片到oss*/			
			uploadFile($ossClient, $bucket, $img_url, $_FILES['img']['tmp_name'],$_FILES['img']['type']);				
        }
    }

    if ($file_url == '')
    {
        $file_url = $_POST['file_url'];
    }
	if ($img_url == '')
    {
        $img_url = $_POST['img_url'];
    }
    /* 计算文章打开方式 */
    if ($file_url == '')
    {
        $open_type = 0;
    }
    else
    {
        $open_type = $_POST['FCKeditor1'] == '' ? 1 : 2;
    }

    /*插入数据*/
    $add_time = gmtime();
    if (empty($_POST['cat_id']))
    {
        $_POST['cat_id'] = 0;
    }
	if($_POST[is_original]==2){
		$reprinted=$_POST[reprinted];
	}else{
		$reprinted="";
	}
	$sql=" select keyword,count from ".$GLOBALS['ecs']->table('admin_keywords')." where admin_id='$_SESSION[admin_id]'";
	$getkeywords=$GLOBALS['db']->getAll($sql);
	$arr_keywords=explode(" ", "$_POST[keywords]");
	

	foreach($arr_keywords as $var){
		if($var!=''){
//			$sql=" select key_id from ".$GLOBALS['ecs']->table('admin_keywords')." where keyword = '$var' and admin_id='$_SESSION[admin_id]'";
//			$r=$GLOBALS['db']->getOne($sql);
			$r=0;
			
			foreach($getkeywords as $v){
				if(@$v['keyword']==$var){
					$r=1;
					$m=$key;
					break;
				}
			}
				
				if(!$r){
					$sql=" insert into ".$GLOBALS['ecs']->table('admin_keywords')." (keyword,count,admin_id) value ( '$var', 0 ,'$_SESSION[admin_id]')";	
					$GLOBALS['db']->query($sql);
				}else{
					$count=$getkeywords[$m]['count']=$getkeywords[$m]['count']+1;
				
					$sql=" update ".$GLOBALS['ecs']->table('admin_keywords')." set count='$count' where keyword = '$var'";
					$GLOBALS['db']->query($sql);
				}	
		}
		
	}
    $sql = "INSERT INTO ".$ecs->table('article')."(title,subtitle,admin_id, cat_id, article_type, is_open, is_hot, author, ".
                "author_email, keywords, content, add_time, file_url, img_url, open_type, link, description,original_content,copyright_id) ".
            "VALUES ('$_POST[title]','$_POST[subtitle]', '$_SESSION[admin_id]', '$_POST[article_cat]', '$_POST[article_type]', '$_POST[is_open]', '$_POST[is_hot]', ".
                "'$_POST[author]', '$_POST[author_email]', trim('$_POST[keywords]'), '$_POST[FCKeditor1]', ".
                "'$add_time', '$file_url','$img_url', '$open_type', '$_POST[link_url]', '$_POST[description]','$reprinted','$_POST[copyright_id]')";
    $db->query($sql);

    /* 处理关联商品 */
    $article_id = $db->insert_id();
    $sql = "UPDATE " . $ecs->table('goods_article') . " SET article_id = '$article_id' WHERE article_id = 0";
    $db->query($sql);
	
    handle_gallery_image($article_id, $_FILES['img_url'], $_POST['img_desc'],$ossClient, $bucket);

    $link[0]['text'] = $_LANG['continue_add'];
    $link[0]['href'] = 'article.php?act=add';

    $link[1]['text'] = $_LANG['back_list'];
    $link[1]['href'] = 'article.php?act=list';

    admin_log($_POST['title'],'add','article');

    clear_cache_files(); // 清除相关的缓存文件

    sys_msg($_LANG['articleadd_succeed'],0, $link);
}

/*------------------------------------------------------ */
//-- 编辑
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'edit')
{
    /* 权限判断 */
    admin_priv('article_look');

    /* 取文章数据 */
//  $sql = "SELECT * FROM " .$ecs->table('article'). " WHERE article_id='$_REQUEST[id]'";
//  $article = $db->GetRow($sql);
	 $sql = "SELECT a.*,c.copyright_type FROM " .$ecs->table('article')." as a  ".
    "left join ".$ecs->table('copyright')." as c on a.copyright_id= c.copyright_id".
    " WHERE a.article_id='$_REQUEST[id]'";
    $article = $db->GetRow($sql);

    /* 创建 html editor */
    $img_tag = '<img src="';
    create_html_editor('FCKeditor1',str_replace($img_tag,$img_tag.$ossHost,$article['content']));

	/* 提取文章内图片 */
//	$content = str_replace($img_tag,$img_tag.$ossHost,$article['content']);
	$image_list = get_articles_img($article['content'],$img_tag, '"');
    if($image_list){
	    $smarty->assign('img_count', $image_list['count']);	    	
		$image_arr = array();
		foreach($image_list['url'] as $k=>$v){
			$desc = '';
			$sql = 'select img_desc  from '.$GLOBALS['ecs']->table('article_img_desc')." where article_id = $_REQUEST[id] and img_url = '".strrchr($v,'/')."'";
			$desc = $db->GetOne($sql);			
			array_push($image_arr,array('url'=>$ossHost.$v,'desc'=>$desc));
		}    		
	    $smarty->assign('image_list', $image_arr);	    	
    }
	
    /* 取得分类、品牌 */
    $smarty->assign('goods_cat_list', cat_list());
    $smarty->assign('brand_list', get_brand_list());
	$sql=" select * from".$GLOBALS['ecs']->table('copyright_type');	
	$getcopyright_type=$GLOBALS['db']->getAll($sql);
	$smarty->assign('getcopyright_type',$getcopyright_type);
	
	$smarty->assign('goods_article_list', get_articles_link($article['article_id']));
    /* 取得关联商品 */
    $goods_list = get_article_goods($_REQUEST['id']);
    $smarty->assign('goods_list', $goods_list);

    /* 取得图文相册 */
	$sql = "SELECT * FROM " . $ecs->table('article_gallery') . " WHERE article_id = '$_REQUEST[id]' ORDER BY sort_order,img_id";
	$img_list = $db->getAll($sql);
	if (!empty($img_list))
	{
		foreach($img_list as $k => $v)
		{
			$img_list[$k]['img_url'] = OSS_HOST.$v['img_url'];
		}
		$smarty->assign('img_list', $img_list);
	}	
		
	$sql=" select keyword from ".$GLOBALS['ecs']->table('admin_keywords')." where admin_id='$_SESSION[admin_id]' order by count desc limit 0,20 ";
	$getkeywords=$GLOBALS['db']->getAll($sql);
	$smarty->assign('getkeywords',     $getkeywords);		    
    $smarty->assign('article',     $article);
    $smarty->assign('cat_select',  article_cat_list(0, $article['cat_id']));
	
    $smarty->assign('ur_here',     $_LANG['article_edit']);
    $smarty->assign('action_link', array('text' => $_LANG['03_article_list'], 'href' => 'article.php?act=list&' . list_link_postfix()));
    $smarty->assign('form_action', 'update');

    assign_query_info();
    $smarty->display('article_info.htm');
}

if ($_REQUEST['act'] =='update')
{
    /* 权限判断 */
    admin_priv('article_manage');

    /*检查文章名是否相同*/
    $is_only = $exc->is_only('title', $_POST['title'], $_POST['id'], "cat_id = '$_POST[article_cat]'");

    if (!$is_only)
    {
        sys_msg(sprintf($_LANG['title_exist'], stripslashes($_POST['title'])), 1);
    }


    if (empty($_POST['cat_id']))
    {
        $_POST['cat_id'] = 0;
    }

	/* 编辑时处理相册图片排序 */
	
    if (isset($_POST['old_img_sort']))

    {

        foreach ($_POST['old_img_sort'] AS $img_id => $img_sort)

        {

            $sql = "UPDATE " . $ecs->table('article_gallery') . " SET sort_order = '$img_sort' WHERE img_id = '$img_id' LIMIT 1";

            $db->query($sql);

        }

    }	
	
	//图片缩图
	    if (isset($_FILES['file']['error'])) // php 4.2 版本才支持 error

    {
    	
		if ($_FILES['file']['error'] == 0)

        {

            if (!$image->check_img_type($_FILES['file']['type']))

            {

               sys_msg($_LANG['dthumbimg_url']);

            }

        }
    	 if ($_FILES['file']['error'] == 1)

        {

            if (!$image->check_img_type($_FILES['file']['type']))

            {

               sys_msg(sprintf($_LANG['thumbimg_url_too_big'],$php_maxsize), 1,  array(), false);

            }

        }

        elseif ($_FILES['file']['error'] == 2)

        {

            sys_msg(sprintf($_LANG['thumbimg_url_too_big'], $php_maxsize), 1, array(), false);

        }


    }else{
    	if ($_FILES['file']['tmp_name'] != 'none')

        {

            if (!$image->check_img_type($_FILES['file']['type']))

            {



                 sys_msg($_LANG['dthumbimg_url']);;

            }

        }
    }
		// 视频缩图验证
	    if (isset($_FILES['img']['error'])) // php 4.2 版本才支持 error

    {
    	
		if ($_FILES['img']['error'] == 0)

        {

            if (!$image->check_img_type($_FILES['img']['type']))

            {

               sys_msg($_LANG['vidioimg_url']);

            }

        }
    	 if ($_FILES['img']['error'] == 1)

        {

            if (!$image->check_img_type($_FILES['img']['type']))

            {

               sys_msg(sprintf($_LANG['vidioimg_url_too_big'],$php_maxsize), 1,  array(), false);

            }

        }

        elseif ($_FILES['img']['error'] == 2)

        {

            sys_msg(sprintf($_LANG['vidioimg_url_too_big'], $php_maxsize), 1, array(), false);

        }


    }else{
    	if ($_FILES['img']['tmp_name'] != 'none')

        {

            if (!$image->check_img_type($_FILES['file']['type']))

            {



                 sys_msg($_LANG['vidioimg_url']);;

            }

        }
    }
	// 图文图片验证

	foreach ($_FILES['img_url']['error'] AS $key => $value) {
		
		if ($value == 0) {
			if (!$image -> check_img_type($_FILES['img_url']['type'][$key])) {
				sys_msg(sprintf($_LANG['invalid_img_url'], $key + 1), 1, array(), false);
			}
		} elseif ($value == 1) {
			sys_msg(sprintf($_LANG['img_url_too_big'], $key + 1, $php_maxsize), 1, array(), false);
		} elseif ($_FILES['img_url']['error'] == 2) {
			sys_msg(sprintf($_LANG['img_url_too_big'], $key + 1, $htm_maxsize), 1, array(), false);
		}
	}
				
    handle_gallery_image($_POST[id], $_FILES['img_url'], $_POST['img_desc'],$ossClient, $bucket);
		
    /* 取得文件地址 */
    $file_url = '';
    if (empty($_FILES['file']['error']) || (!isset($_FILES['file']['error']) && isset($_FILES['file']['tmp_name']) && $_FILES['file']['tmp_name'] != 'none'))
    {
        // 检查文件格式
        if (!check_file_type($_FILES['file']['tmp_name'], $_FILES['file']['name'], $allow_file_types))
        {
            sys_msg($_LANG['invalid_file']);
        }

        // 复制文件
        $res = check_article_file($_FILES['file']);
        if ($res != false)
        {
            $file_url = $res;
		    /* 上传图片到oss*/			
			uploadFile($ossClient, $bucket, $file_url, $_FILES['file']['tmp_name'],$_FILES['file']['type']);						
        }
    }
	/* 取得视频地址 */
    $img_url = '';
    if ((isset($_FILES['img']['error']) && $_FILES['img']['error'] == 0) || (!isset($_FILES['img']['error']) && isset($_FILES['img']['tmp_name']) && $_FILES['img']['tmp_name'] != 'none'))
    {
        // 检查文件格式
        if (!check_file_type($_FILES['img']['tmp_name'], $_FILES['img']['name'], $allow_file_types))
        {
            sys_msg($_LANG['invalid_file']);
        }

        // 复制文件
        $res = check_article_file($_FILES['img']);
        if ($res != false)
        {
            $img_url = $res;
		    /* 上传图片到oss*/			
			uploadFile($ossClient, $bucket, $img_url, $_FILES['img']['tmp_name'],$_FILES['img']['type']);				
        }
    }
    if ($file_url == '')
    {
        $file_url = $_POST['file_url'];
    }
	if ($img_url == '')
    {
        $img_url = $_POST['img_url'];
    }

    /* 计算文章打开方式 */
    if ($file_url == '')
    {
        $open_type = 0;
    }
    else
    {
        $open_type = $_POST['FCKeditor1'] == '' ? 1 : 2;
    }

    /* 如果 file_url 跟以前不一样，且原来的文件是本地文件，删除原来的文件 */
    $sql = "SELECT file_url,img_url FROM " . $ecs->table('article') . " WHERE article_id = '$_POST[id]'";
    $old_url = $db->getRow($sql);
    if ($old_url['file_url'] != '' && $old_url['file_url'] != $file_url && strpos($old_url['file_url'], 'http://') === false && strpos($old_url['file_url'], 'https://') === false)
    {
//      @unlink(ROOT_PATH . $old_url);
		/* 删除oss上的图片 */				
		deleteObject($ossClient, $bucket, $old_url['file_url']);
		
//		var_dump($old_url);		
    }
	$old_url = $db->getRow($sql);
    if ($old_url['img_url'] != '' && $old_url['img_url'] != $img_url && strpos($old_url['img_url'], 'http://') === false && strpos($old_url['img_url'], 'https://') === false)
    {
//      @unlink(ROOT_PATH . $old_url);
		/* 删除oss上的图片 */				
		deleteObject($ossClient, $bucket, $old_url['img_url']);
		
//		var_dump($old_url);		
    }
	
//	var_dump($img_url);
//	var_dump($_POST['img_url']);
//	var_dump($file_url);
//	var_dump($_POST['file_url']);		
//	$content = $_POST['FCKeditor1'];	
//	var_dump($content);
//	var_dump($ossHost);	
	$sql=" select keyword,count from ".$GLOBALS['ecs']->table('admin_keywords')." where admin_id='$_SESSION[admin_id]'";
	$getkeywords=$GLOBALS['db']->getAll($sql);
	$arr_keywords=explode(" ", "$_POST[keywords]");
	

	foreach($arr_keywords as $var){
		if($var!=''){
//			$sql=" select key_id from ".$GLOBALS['ecs']->table('admin_keywords')." where keyword = '$var' and admin_id='$_SESSION[admin_id]'";
//			$r=$GLOBALS['db']->getOne($sql);
			$r=0;
			
			foreach($getkeywords as $key=>$v){
				if(@$v['keyword']==$var){
					$r=1;
					$m=$key;
					break;
				}
			}
				
				if(!$r){
					$sql=" insert into ".$GLOBALS['ecs']->table('admin_keywords')." (keyword,count,admin_id) value ('$var',0,'$_SESSION[admin_id]')";	
					$GLOBALS['db']->query($sql);
				}else{
					$count=$getkeywords[$m]['count']=$getkeywords[$m]['count']+1;
				
					$sql=" update ".$GLOBALS['ecs']->table('admin_keywords')." set count='$count' where keyword = '$var' and admin_id=$_SESSION[admin_id]";
					$GLOBALS['db']->query($sql);
				}	
		}
		
	}
	
	$content = str_replace($ossHost,'/',$_POST['FCKeditor1']);
//	var_dump($content);
	if($_POST[is_original]==2){
		$reprinted=$_POST[reprinted];
	}else{
		$reprinted="";
	}
    if ($exc->edit("title='$_POST[title]',subtitle='$_POST[subtitle]',copyright_id='$_POST[copyright_id]',original_content='$reprinted', cat_id='$_POST[article_cat]', article_type='$_POST[article_type]', is_open='$_POST[is_open]', is_hot='$_POST[is_hot]', author='$_POST[author]', author_email='$_POST[author_email]', keywords =trim('$_POST[keywords]'), file_url ='$file_url', img_url ='$img_url', open_type='$open_type', content='$content', link='$_POST[link_url]', description = '$_POST[description]'", $_POST['id']))
    {
    	$article_id = $_POST['id'];
		/* 删除已有图赏模式描述 */   	
		$db->query("DELETE FROM " . $ecs->table('article_img_desc') . " WHERE " . " article_id = $article_id");
		/* 添加文章内容图赏描述 */
		if($_POST['img_tips']){
			foreach ($_POST['img_tips'] AS $k => $v) {
			if ($v){
				$add_time = gmtime();
				$img_url = strrchr($_POST['img_tips_name'][$k],"/");
				$sql = "INSERT INTO " . $GLOBALS['ecs'] -> table('article_img_desc') . " (article_id, img_url, img_desc,add_time) " . "VALUES ('$article_id', '$img_url', '$v', '$add_time')";
				$GLOBALS['db'] -> query($sql);						
			}
			}
		}
						
		
        $link[0]['text'] = $_LANG['back_list'];
        $link[0]['href'] = 'article.php?act=list&' . list_link_postfix();

        $note = sprintf($_LANG['articleedit_succeed'], stripslashes($_POST['title']));
        admin_log($_POST['title'], 'edit', 'article');

        clear_cache_files();

        sys_msg($note, 0, $link);
    }
    else
    {
        die($db->error());
    }
}

/*------------------------------------------------------ */
//-- 编辑文章主题
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_title')
{
    check_authz_json('article_manage');

    $id    = intval($_POST['id']);
    $title = json_str_iconv(trim($_POST['val']));

    /* 检查文章标题是否重复 */
    if ($exc->num("title", $title, $id) != 0)
    {
        make_json_error(sprintf($_LANG['title_exist'], $title));
    }
    else
    {
        if ($exc->edit("title = '$title'", $id))
        {
            clear_cache_files();
            admin_log($title, 'edit', 'article');
            make_json_result(stripslashes($title));
        }
        else
        {
            make_json_error($db->error());
        }
    }
}

/*------------------------------------------------------ */
//-- 切换是否显示
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_show')
{
    check_authz_json('article_manage');
	
    $id     = intval($_POST['id']);
    $val    = intval($_POST['val']);

    $exc->edit("is_open = '$val'", $id);
    clear_cache_files();

    make_json_result($val);
}

/*------------------------------------------------------ */
//-- 切换文章重要性
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_type')
{
    check_authz_json('article_manage');

    $id     = intval($_POST['id']);
    $val    = intval($_POST['val']);

    $exc->edit("article_type = '$val'", $id);
    clear_cache_files();

    make_json_result($val);
}

/*------------------------------------------------------ */
//-- 切换文章重要性
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_hot')
{
    check_authz_json('article_manage');

    $id     = intval($_POST['id']);
    $val    = intval($_POST['val']);

    $exc->edit("is_hot = '$val'", $id);
    clear_cache_files();

    make_json_result($val);
}



/*------------------------------------------------------ */
//-- 删除文章主题
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    check_authz_json('article_delect');

    $id = intval($_GET['id']);

    /* 删除原来的文件 */
    $sql = "SELECT file_url,img_url FROM " . $ecs->table('article') . " WHERE article_id = '$id'";
    $old_url = $db->getRow($sql);
    if ($old_url['file_url'] != '' && strpos($old_url['file_url'], 'http://') === false && strpos($old_url['file_url'], 'https://') === false)
    {
//      @unlink(ROOT_PATH . $old_url);
		/* 删除oss上的图片 */				
		deleteObject($ossClient, $bucket, $old_url['file_url']);		
    }
	 /* 删除原来的文件 */

    if ($old_url['img_url'] != '' && strpos($old_url['img_url'], 'http://') === false && strpos($old_url['img_url'], 'https://') === false)
    {
//      @unlink(ROOT_PATH . $old_url);
		/* 删除oss上的图片 */				
		deleteObject($ossClient, $bucket, $old_url['img_url']);		
    }

    $name = $exc->get_name($id);
    if ($exc->drop($id))
    {
        $db->query("DELETE FROM " . $ecs->table('comment') . " WHERE " . "comment_type = 1 AND id_value = $id");
		/*删除对应图文相册*/
		$sql = "SELECT img_url FROM " . $ecs->table('article_gallery') . " WHERE article_id = '$id'";
		$img_list = $db->getAll($sql);		
		if ($img_list)
		{
			foreach($img_list as $k => $v)
			{
				/* 删除oss上的图片 */				
				deleteObject($ossClient, $bucket, $v['img_url']);						
			}
	        $db->query("DELETE FROM " . $ecs->table('article_gallery') . " WHERE article_id = $id");					
		}
					        
        admin_log(addslashes($name),'remove','article');
        clear_cache_files();
    }

    $url = 'article.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 将商品加入关联
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add_link_goods')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('article_manage');

    $add_ids = $json->decode($_GET['add_ids']);
    $args = $json->decode($_GET['JSON']);
    $article_id = $args[0];

    if ($article_id == 0)
    {
        $article_id = $db->getOne('SELECT MAX(article_id)+1 AS article_id FROM ' .$ecs->table('article'));
    }

    foreach ($add_ids AS $key => $val)
    {
        $sql = 'INSERT INTO ' . $ecs->table('goods_article') . ' (goods_id, article_id) '.
               "VALUES ('$val', '$article_id')";
        $db->query($sql, 'SILENT') or make_json_error($db->error());
    }

    /* 重新载入 */
    $arr = get_article_goods($article_id);
    $opt = array();

    foreach ($arr AS $key => $val)
    {
        $opt[] = array('value'  => $val['goods_id'],
                        'text'  => $val['goods_name'],
                        'data'  => '');
    }

    make_json_result($opt);
}


/*------------------------------------------------------ */

//-- 搜索文章

/*------------------------------------------------------ */



elseif ($_REQUEST['act'] == 'get_article_list')

{

    include_once(ROOT_PATH . 'includes/cls_json.php');

    $json = new JSON;



    $filters =(array) $json->decode(json_str_iconv($_GET['JSON']));



    $where = " WHERE cat_id > 0 ";

    if (!empty($filters['title']))

    {

        $keyword  = trim($filters['title']);

        $where   .=  " AND title LIKE '%" . mysql_like_quote($keyword) . "%' ";

    }



    $sql        = 'SELECT article_id, title FROM ' .$ecs->table('article'). $where.

                  'ORDER BY article_id DESC LIMIT 50';

    $res        = $db->query($sql);

    $arr        = array();



    while ($row = $db->fetchRow($res))

    {

        $arr[]  = array('value' => $row['article_id'], 'text' => $row['title'], 'data'=>'');

    }



    make_json_result($arr);

}

/*------------------------------------------------------ */
//-- 将文章加入关联
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add_link_article')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('article_manage');

    $add_ids = $json->decode($_GET['add_ids']);
    $args = $json->decode($_GET['JSON']);
    $article_id = $args[0];

    if ($article_id == 0)
    {
        $article_id = $db->getOne('SELECT MAX(article_id)+1 AS article_id FROM ' .$ecs->table('article'));
    }

    foreach ($add_ids AS $key => $val)
    {
        $sql = 'INSERT INTO ' . $ecs->table('article_article') . ' (article_link_id, article_id) '.
               "VALUES ('$val', '$article_id')";
        $db->query($sql, 'SILENT') ;
    }

    /* 重新载入 */
    $arr = get_link_article($article_id);
    $opt = array();

    foreach ($arr AS $key => $val)
    {
        $opt[] = array('value'  => $val['article_id'],
                        'text'  => $val['title'],
                        'data'  => '');
    }

    make_json_result($opt);
}
/*------------------------------------------------------ */
//-- 将文章删除关联
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_link_article')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('article_manage');

    $drop_article     = $json->decode($_GET['drop_ids']);
    $arguments      = $json->decode($_GET['JSON']);
    $article_id     = $arguments[0];

    if ($article_id == 0)
    {
        $article_id = $db->getOne('SELECT MAX(article_id)+1 AS article_id FROM ' .$ecs->table('article'));
    }

    $sql = "DELETE FROM " . $ecs->table('article_article').
            " WHERE article_id = '$article_id' AND article_link_id " .db_create_in($drop_article);
    $db->query($sql, 'SILENT') or make_json_error($db->error());

    /* 重新载入 */
    $arr = get_link_article($article_id);
    $opt = array();

    foreach ($arr AS $key => $val)
    {
         $opt[] = array('value'  => $val['article_id'],
                        'text'  => $val['title'],
                        'data'  => '');
    }

    make_json_result($opt);
}
/*------------------------------------------------------ */
//-- 将商品删除关联
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_link_goods')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('article_manage');

    $drop_goods     = $json->decode($_GET['drop_ids']);
    $arguments      = $json->decode($_GET['JSON']);
    $article_id     = $arguments[0];

    if ($article_id == 0)
    {
        $article_id = $db->getOne('SELECT MAX(article_id)+1 AS article_id FROM ' .$ecs->table('article'));
    }

    $sql = "DELETE FROM " . $ecs->table('goods_article').
            " WHERE article_id = '$article_id' AND goods_id " .db_create_in($drop_goods);
    $db->query($sql, 'SILENT') or make_json_error($db->error());

    /* 重新载入 */
    $arr = get_article_goods($article_id);
    $opt = array();

    foreach ($arr AS $key => $val)
    {
        $opt[] = array('value'  => $val['goods_id'],
                        'text'  => $val['goods_name'],
                        'data'  => '');
    }

    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 搜索商品
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'get_goods_list')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $arr = get_goods_list($filters);
    $opt = array();

    foreach ($arr AS $key => $val)
    {
        $opt[] = array('value' => $val['goods_id'],
                        'text' => $val['goods_name'],
                        'data' => $val['shop_price']);
    }

    make_json_result($opt);
}

/*------------------------------------------------------ */

//-- 删除图片

/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'drop_image')

{

    check_authz_json('article_manage');



    $img_id = empty($_REQUEST['img_id']) ? 0 : intval($_REQUEST['img_id']);



    /* 删除图片文件 */

    $sql = "SELECT img_url" .

            " FROM " . $GLOBALS['ecs']->table('article_gallery') .

            " WHERE img_id = '$img_id'";

    $row = $GLOBALS['db']->getRow($sql);



    if ($row['img_url'] != '')

    {
		/* 删除oss上的图片 */				
		deleteObject($ossClient, $bucket, $row['img_url']);	        

    }



    /* 删除数据 */

    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('article_gallery') . " WHERE img_id = '$img_id' LIMIT 1";

    $GLOBALS['db']->query($sql);



    clear_cache_files();

    make_json_result($img_id,"success");

}


/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'batch')
{
    /* 批量删除 */
    if (isset($_POST['type']))
    {
        if ($_POST['type'] == 'button_remove')
        {
            admin_priv('article_manage');

            if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes']))
            {
                sys_msg($_LANG['no_select_article'], 1);
            }

            /* 删除原来的文件 */
            $sql = "SELECT file_url FROM " . $ecs->table('article') .
                    " WHERE article_id " . db_create_in(join(',', $_POST['checkboxes'])) .
                    " AND file_url <> ''";

            $res = $db->query($sql);
            while ($row = $db->fetchRow($res))
            {
                $old_url = $row['file_url'];
                if (strpos($old_url, 'http://') === false && strpos($old_url, 'https://') === false)
                {
//                  @unlink(ROOT_PATH . $old_url);
					/* 删除oss上的图片 */				
					deleteObject($ossClient, $bucket, $old_url);
                }
			
            }
			/* 删除原来的文件 */
            $sql = "SELECT img_url FROM " . $ecs->table('article') .
                    " WHERE article_id " . db_create_in(join(',', $_POST['checkboxes'])) .
                    " AND img_url <> ''";

            $res = $db->query($sql);
            while ($row = $db->fetchRow($res))
            {
                $old_url = $row['img_url'];
                if (strpos($old_url, 'http://') === false && strpos($old_url, 'https://') === false)
                {
//                  @unlink(ROOT_PATH . $old_url);
					/* 删除oss上的图片 */				
					deleteObject($ossClient, $bucket, $old_url);
                }
			
            }

            foreach ($_POST['checkboxes'] AS $key => $id)
            {
                if ($exc->drop($id))
                {
                    $name = $exc->get_name($id);
                    admin_log(addslashes($name),'remove','article');
					
					/*删除对应图文相册*/
					$sql = "SELECT img_url FROM " . $ecs->table('article_gallery') . " WHERE article_id = '$id'";
					$img_list = $db->getAll($sql);		
					if ($img_list)
					{
						foreach($img_list as $k => $v)
						{
							/* 删除oss上的图片 */				
							deleteObject($ossClient, $bucket, $v['img_url']);						
						}
				        $db->query("DELETE FROM " . $ecs->table('article_gallery') . " WHERE article_id = $id");					
					}
                }
            }

        }

        /* 批量隐藏 */
        if ($_POST['type'] == 'button_hide')
        {
//          check_authz_json('article_manage');
			admin_priv('article_manage');
            if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes']))
            {
                sys_msg($_LANG['no_select_article'], 1);
            }

            foreach ($_POST['checkboxes'] AS $key => $id)
            {
              $exc->edit("is_open = '0'", $id);
            }
        }

        /* 批量显示 */
        if ($_POST['type'] == 'button_show')
        {
//          check_authz_json('article_manage');
			admin_priv('article_manage');
            if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes']))
            {
                sys_msg($_LANG['no_select_article'], 1);
            }

            foreach ($_POST['checkboxes'] AS $key => $id)
            {
              $exc->edit("is_open = '1'", $id);
            }
        }

        /* 批量移动分类 */
        if ($_POST['type'] == 'move_to')
        {
//          check_authz_json('article_manage');
			admin_priv('article_manage');
            if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes']) )
            {
                sys_msg($_LANG['no_select_article'], 1);
            }

            if(!$_POST['target_cat'])
            {
                sys_msg($_LANG['no_select_act'], 1);
            }
            
            foreach ($_POST['checkboxes'] AS $key => $id)
            {
              $exc->edit("cat_id = '".$_POST['target_cat']."'", $id);
            }
        }
    }

    /* 清除缓存 */
    clear_cache_files();
    $lnk[] = array('text' => $_LANG['back_list'], 'href' => 'article.php?act=list');
    sys_msg($_LANG['batch_handle_ok'], 0, $lnk);
}
elseif ($_REQUEST['act'] == 'original')
{
	$is_original=$_GET['is_number'];
	$sql=" select * from ".$GLOBALS['ecs']->table('copyright')." where copyright_type='$is_original'";
	$result=$GLOBALS['db']->getAll($sql);
	foreach($result as $key=>$val){
		if($result[$key]['img_url']){
			$result[$key]['img_url']=OSS_HOST.$result[$key]['img_url'];
		}
		
	}
//	$yy='original';
//	if($is_original==1){
//		$result[original]=$_CFG['original'];
//		$result[code_logo]=OSS_HOST.$_CFG['code_logo'];
//	}else{
//		$result[reprinted]=$_CFG['reprinted'];
//	}

//	echo $_LANG['cfg_name'][$result['code']];
	echo json_encode($result);
}
elseif ($_REQUEST['act'] == 'getShowtype')
{
	$cat_type=$_GET['cat_type'];
	$sql=" select show_type from ".$GLOBALS['ecs']->table('article_cat')." where cat_id='$cat_type'";
	$result=$GLOBALS['db']->getOne($sql);
	echo json_encode($result);
}

/* 把商品删除关联 */
function drop_link_goods($goods_id, $article_id)
{
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('goods_article') .
            " WHERE goods_id = '$goods_id' AND article_id = '$article_id' LIMIT 1";
    $GLOBALS['db']->query($sql);
    create_result(true, '', $goods_id);
}

/* 取得文章关联商品 */
function get_article_goods($article_id)
{
    $list = array();
    $sql  = 'SELECT g.goods_id, g.goods_name'.
            ' FROM ' . $GLOBALS['ecs']->table('goods_article') . ' AS ga'.
            ' LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON g.goods_id = ga.goods_id'.
            " WHERE ga.article_id = '$article_id'";
    $list = $GLOBALS['db']->getAll($sql);

    return $list;
}

/* 取得文章关联文章 */
function get_link_article($article_id)
{
    $list = array();
    $sql  = 'SELECT g.article_id, g.title'.
            ' FROM ' . $GLOBALS['ecs']->table('article_article') . ' AS ga'.
            ' LEFT JOIN ' . $GLOBALS['ecs']->table('article') . ' AS g ON g.article_id = ga.article_link_id'.
            " WHERE ga.article_id = '$article_id'";
    $list = $GLOBALS['db']->getAll($sql);

    return $list;
}

/* 获得文章列表 */
function get_articleslist()
{
    $result = get_filter();
    if ($result === false)
    {
        $filter = array();
        $filter['keyword']    = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        $filter['cat_id'] = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'a.add_time' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

//      $where = ' AND (ac.show_type =1 OR ac.show_type=2 OR ac.show_type=4 OR ac.show_type=5) ';
        if (!empty($filter['keyword']))
        {
            $where = " AND a.title LIKE '%" . mysql_like_quote($filter['keyword']) . "%'";
        }
        if ($filter['cat_id'])
        {
            $where .= " AND a." . get_article_children($filter['cat_id']);
        }
		
		if (!admin_priv('all_goods','',false))
		{
			$where .= "AND a.admin_id = '$_SESSION[admin_id]'";			
		}
	
        /* 文章总数 */
        $sql = 'SELECT COUNT(*) FROM ' .$GLOBALS['ecs']->table('article'). ' AS a '.
               'LEFT JOIN ' .$GLOBALS['ecs']->table('article_cat'). ' AS ac ON ac.cat_id = a.cat_id '.
               'WHERE 1 ' .$where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        $filter = page_and_size($filter);

        /* 获取文章数据 */
        $sql = 'SELECT a.* , ac.cat_name '.
               'FROM ' .$GLOBALS['ecs']->table('article'). ' AS a '.
               'LEFT JOIN ' .$GLOBALS['ecs']->table('article_cat'). ' AS ac ON ac.cat_id = a.cat_id '.
               'WHERE 1 ' .$where. ' ORDER by '.$filter['sort_by'].' '.$filter['sort_order'];

        $filter['keyword'] = stripslashes($filter['keyword']);
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $arr = array();
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
    	
        $rows['date'] = local_date($GLOBALS['_CFG']['time_format'], $rows['add_time']);
		//获取管理员名称
		if ($rows['admin_id']>0)
		{
			$sql = 'SELECT user_name FROM ' .$GLOBALS['ecs']->table('admin_user'). " WHERE user_id = '$rows[admin_id]'";
	        $rows['admin_name']  = $GLOBALS['db']->getOne($sql);      
		}
		
		$sql=" select count(*) from ".$GLOBALS['ecs']->table('article_comment')." where id_value=$rows[article_id] and comment_type=1";
		$rows['article_comment']=$GLOBALS['db']->getOne($sql);
		
		$arr[] = $rows;
       
    }
    return array('arr' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

/* 上传文件 */
function upload_article_file($upload)
{
    if (!make_dir("../" . DATA_DIR . "/article"))
    {
        /* 创建目录失败 */
        return false;
    }

    $filename = cls_image::random_filename() . substr($upload['name'], strpos($upload['name'], '.'));
    $path     = ROOT_PATH. DATA_DIR . "/article/" . $filename;

    if (move_upload_file($upload['tmp_name'], $path))
    {
        return DATA_DIR . "/article/" . $filename;
    }
    else
    {
        return false;
    }
}

/**

 * 获得文章中的图片

 *

 * @access  public

 * @param   $content 文章内容
 * @param   $begin_tag 起始标记
 * @param   $end_tag 结束标记
 * @return  array

 */

function get_articles_img($content, $begin_tag, $end_tag)
{
	/* 提取文章内图片 */
	$image_list['url'] = array();
	$image_list['count'] = 0;
	$begin = 0;
	while(strpos($content, $begin_tag, $begin))
	{
		$img_begin = strpos($content, $begin_tag, $begin)+strlen($begin_tag);
		$img_end = strpos($content, $end_tag, $img_begin);
		$img = substr($content, $img_begin, $img_end-$img_begin);
		
		//填充文章图片
		array_push($image_list['url'],$img);
		$image_list['count']++;
		
		$begin = $img_end;		
	}

    return $image_list;

}


/**

 * 获得文章的关联文章

 *

 * @access  public

 * @param   integer $goods_id

 * @return  array

 */

function get_articles_link($article_id)

{
	

    $sql = "SELECT g.article_id, a.title " .

            "FROM " .$GLOBALS['ecs']->table('article_article') . " AS g, " .

                $GLOBALS['ecs']->table('article') . " AS a " .

            "WHERE g.article_id = '$article_id' " .

            "AND g.article_link_id = a.article_id ";

    if ($article_id == 0)

    {

        $sql .= " AND g.admin_id = '$_SESSION[admin_id]'";

    }

    $row = $GLOBALS['db']->getAll($sql);

    return $row;

}
/**

 * 保存图文的相册图片
 * @param   int     $article_id
 * @param   array   $image_files
 * @param   array   $image_descs
 * @return  void
 */
function handle_gallery_image($article_id, $image_files, $image_descs,$ossClient, $bucket) {
	/* 是否处理缩略图 */
		
	foreach ($image_files['error'] AS $key => $value) {
		
		/* 是否成功上传 */
		$flag = false;
		if (isset($image_files['error'])) {
			if ($image_files['error'][$key] == 0) {
				$flag = true;
			}
		} else {
			if ($image_files['tmp_name'][$key] != 'none') {
				$flag = true;
			}
		}
		if ($flag) {
			$upload = array('name' => $image_files['name'][$key], 'type' => $image_files['type'][$key], 'tmp_name' => $image_files['tmp_name'][$key], 'size' => $image_files['size'][$key], );
			if (isset($image_files['error'])) {
				$upload['error'] = $image_files['error'][$key];
			}
			$img_original = $GLOBALS['image'] -> upload_image($upload);
			if ($img_original === false) {
				sys_msg($GLOBALS['image'] -> error_msg(), 1, array(), false);
			}
			$img_url = $img_original;

			$img_url = reformat_image_name($article_id, $img_url,$ossClient, $bucket);
			$add_time = gmtime();
			$sql = "INSERT INTO " . $GLOBALS['ecs'] -> table('article_gallery') . " (article_id, img_url, img_desc,add_time) " . "VALUES ('$article_id', '$img_url', '$image_descs[$key]', '$add_time')";
			$GLOBALS['db'] -> query($sql);
			/* 不保留商品原图的时候删除原图 */			
			@unlink('../' . $img_url);			
		} 
	}
}

/**

 * 格式化商品图片名称（按目录存储）

 *

 */
function reformat_image_name($article_id, $source_img,$ossClient, $bucket) {
	$rand_name = gmtime() . sprintf("%03d", mt_rand(1, 999));
	$img_ext = substr($source_img, strrpos($source_img, '.'));
	$dir = 'data/article/image';
//	$sub_dir = $article_id.'/';
    $sub_dir = date('Ym', gmtime());
	if (!make_dir(ROOT_PATH . $dir . '/' . $sub_dir)) {
		return false;
	}
	$img_name = $article_id . '_' . $rand_name;
	if (move_image_file(ROOT_PATH . $source_img, ROOT_PATH . $dir . '/' . $sub_dir . '/' . $img_name . $img_ext)) {
		/* 上传图片到oss*/
		uploadFile($ossClient, $bucket, $dir.'/'.$sub_dir. '/' .$img_name.$img_ext, ROOT_PATH.$dir.'/'.$sub_dir. '/' .$img_name.$img_ext);
		return $dir . '/' . $sub_dir . '/' .$img_name . $img_ext;
	}
	return false;
}

function move_image_file($source, $dest) {

	if (@copy($source, $dest)) {

		@unlink($source);

		return true;

	}

	return false;

}

/* 上传文件 */
function check_article_file($upload)
{
    $filename = cls_image::random_filename() . substr($upload['name'], strpos($upload['name'], '.'));
//  $path     = ROOT_PATH. DATA_DIR . "/article/" . $filename;

    return DATA_DIR . "/article/" . $filename;

}

?>